package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.domain.entity.DeepseekLog;
import com.ruoyi.system.mapper.DeepseekLogMapper;
import com.ruoyi.system.service.IDeepseekLogService;
import com.ruoyi.system.service.IDeepseekService;
import com.ruoyi.system.service.ISysConfigService;
import okhttp3.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;
@Service
public class DeepSeekClient  implements IDeepseekService {
    private static final String API_URL = "https://api.deepseek.com/chat/completions";
    private static final String API_KEY = "sk-fedafa7a616a4751917c64ac4ac986f8"; // 替换为实际API密钥
    private static final String MODEL = "deepseek-reasoner"; // 根据实际模型名称修改

    @Autowired
    private DeepseekLogMapper deepseekLogMapper;
    @Autowired
    private IDeepseekLogService deepseekLogService;


    private final ObjectMapper objectMapper = new ObjectMapper();

    // 创建 OkHttpClient 并设置超时时间
    private final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(180000, TimeUnit.SECONDS) // 连接超时
            .readTimeout(180000, TimeUnit.SECONDS)    // 读取超时
            .writeTimeout(180000, TimeUnit.SECONDS)   // 写入超时
            .build();




    @Override
    public String  deepseekUtil(String userMessage) throws InterruptedException {
        while (true) {
            try {
                System.out.println("deepseek分段进行中...，" );
                String response = new DeepSeekClient().chatCompletion(userMessage,false);
//                System.out.println("API Response:\n" + response);
                return response;
            } catch (IOException e) {
                System.out.println("deepseek进行中...，" );
                Thread.sleep(7000);
            }

        }
    }

    @Override
    public String chatCompletion(String userMessage,Boolean bool) throws IOException {
        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", MODEL);
        List<Map<String, String>> messages = new ArrayList<>();
        Map<String, String> map1 = new HashMap<>();
        map1.put("role", "user");
        map1.put("content", userMessage);
        messages.add(map1);
        requestBody.put("messages", messages);
        // 可调整的常用参数
        requestBody.put("temperature", 0.7);  // 控制随机性（0-2）
        requestBody.put("max_tokens", 3000);  // 最大生成token数
        requestBody.put("top_p", 1.0);        // 核采样阈值
        // 创建HTTP请求
        Request request = new Request.Builder()
                .url(API_URL)
                .post(RequestBody.create(
                        MediaType.parse("application/json"),
                        objectMapper.writeValueAsString(requestBody)
                                ))
                .addHeader("Authorization", "Bearer " + API_KEY)
                .addHeader("Content-Type", "application/json")
                .build();
        // 发送请求并处理响应
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code: " + response);
            }
            // 解析响应
            Map<String, Object> responseMap = objectMapper.readValue(
                    response.body().string(),
                    Map.class
            );
            // 提取生成的回复内容
            List<Map<String, Object>> choices = (List<Map<String, Object>>) responseMap.get("choices");
            if (choices != null && !choices.isEmpty()) {
                Map<String, Object> firstChoice = choices.get(0);
                Map<String, String> message = (Map<String, String>) firstChoice.get("message");
                try {
                    if (bool){
                        DeepseekLog deepseekLog=new DeepseekLog();
                        deepseekLog.setCreateTime(new Date());
                        deepseekLog.setQuestions(userMessage);
                        deepseekLog.setThink(message.get("reasoning_content"));
                        deepseekLog.setAnswered(message.get("content"));
                        deepseekLogMapper.insertDeepseekLog(deepseekLog);
                    }

                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                return message.get("content");
            }
            return "No response content";
        }
    }
}
